<?php

class Plugin extends Zend_Controller_Plugin_Abstract {

    public function preDispatch(Zend_Controller_Request_Abstract $request) {
        $auth = Zend_Auth::getInstance();
        $user = null;
        if ($auth->hasIdentity()) {
            $user = $auth->getIdentity()->username;
            $layout = Zend_Layout::getMvcInstance();
            $view = $layout->getView();
            $view->username = $user;
        }
        $controllerName = $request->getControllerName();
        $actionName = $this->getActionName($request);
        $moduleName = $request->getModuleName();

        switch ($moduleName) {
            case "frontend":
                switch ($controllerName) {
                    case "post":
                        if ($actionName == 'login') {
                            if ($user == null) {
                                $request->setControllerName('user');
                                $request->setActionName('login');
                            } else {
                                $request->setControllerName('index');
                                $request->setActionName('post');
                            }
                        }
                        break;
                    default:
                        break;
                }

                break;
            case "backend";
                if ($user == null) {
                    $request->setControllerName('user');
                    $request->setActionName('login');
                    $request->setModuleName('frontend');
                }
                break;

            default:
                $request->setControllerName('index');
                $request->setActionName('post');
                $request->setModuleName('frontend');
                break;
        }        
        
        
    }

    private function getActionName($request) {
        $actionName = $request->getActionName();
        if ($actionName == NULL) {
            $actionName = 'index';
        }
        return $actionName;
    }
    


}
